import { defineComponent, onMounted, type PropType, ref, watch } from "vue";
import { dictTranslate, type SimpleDict } from "@/api/system";
import { storageSession } from "@pureadmin/utils";

export default defineComponent({
  name: "DictTag",
  props: {
    value: {
      required: true
    },
    code: {
      type: String,
      required: true
    },
    size: {
      type: String as PropType<"large" | "default" | "small">,
      default: "default"
    },
    effect: {
      type: String as PropType<"dark" | "light" | "plain">,
      default: "light"
    },
    type: {
      type: String as PropType<
        "success" | "info" | "warning" | "danger" | "primary"
      >
    },
    text: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const data = ref<SimpleDict>({});
    const realType = ref<string>();
    const color = ref<string>();
    function init(dict: SimpleDict) {
      data.value = dict;
      if (dict.color) {
        if (dict.color.startsWith("#")) {
          color.value = dict.color;
        } else {
          realType.value = dict.color;
        }
      } else {
        color.value = "";
      }
    }
    function loadDict(code: string, value: any) {
      realType.value = props.text ? "" : "primary";
      if (storageSession().getItem<SimpleDict>(`${code}.${value}`)) {
        init(storageSession().getItem<SimpleDict>(`${code}.${value}`));
      } else {
        dictTranslate(code, value).then(res => {
          storageSession().setItem<SimpleDict>(`${code}.${value}`, res);
          init(res);
        });
      }
    }
    watch(
      () => [props.code, props.value],
      () => {
        loadDict(props.code, props.value);
      }
    );
    onMounted(() => {
      loadDict(props.code, props.value);
    });
    return () => {
      if (props.text) {
        return (
          <el-text type={props?.type ?? realType.value} size={props.size}>
            {data.value.label}
          </el-text>
        );
      } else {
        return (
          <el-tag
            size={props.size}
            effect={props.effect}
            type={props?.type ?? realType.value}
            color={color.value}
          >
            {data.value.label}
          </el-tag>
        );
      }
    };
  }
});
